/*
 * @Author: yangrongxin
 * @Date: 2021-09-02 09:08:24
 * @LastEditors: yangrongxin
 * @LastEditTime: 2022-01-18 18:06:07
 */
import { useState, useEffect, useCallback } from 'react';
import { useRouter } from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import { ScrollDataTable, Pie } from '@/components/index';
import { AtIcon } from 'taro-ui';
import { TeamTestReportItem } from './components';
import { getTeamReport } from './service';
import styles from './index.module.less';

const TeamTestReport = () => {
  const [teamData, setTeamData] = useState<any>({
    userProfile: {}, // 对应当前的用户信息
  }); // 设置团队测评报告

  const {
    params: { evaluationId },
  } = useRouter();

  useEffect(() => {
    getTeamReport({
      teamEvaluationId: evaluationId,
    }).then((res: any) => {
      setTeamData(res);
    });
  }, []);

  const {
    teamName,
    createdTime,
    measureList = [],
    riskLevels = [],
    // hearthLevels = {},
    // educations = {}, // 教育字段
    // marriages = {},
    auditComment, // 当前的评阅信息
    userProfile: {
      // 获取当前用户的数据
      userCount, // 用户总数
      manNum, // 男性个数
      womanNum, // 女性个数
      maxAge, // 最大年龄
      minAge, // 最小年龄
      avgAge, // 平均年龄
      standardDeviation, // 标准差
      manPercent, // 男性百分比
      womanPercent, // 女性百分比
      education = {}, // 存储当前的学历数据
      educationPercent = {}, // 学历数据的百分比
      marriage = {}, // 存储当前婚姻的数据
      marriagePercent = {}, // 存储当前婚姻的百分比
    },
  } = teamData;

  console.log('teamData', teamData);

  // const hearthLevelsKeys = Object.keys(hearthLevels); // 心理健康对应的数据key值
  // const educationsKeys = Object.keys(educations); // 获取教育的keys字段
  // const marriagesKeys = Object.keys(marriages); // 获取教育的keys字段

  const getEducationWithIndex = useCallback(
    (index: number, isPecent = false) => (isPecent ? educationPercent[`edu${index}`] : education[`edu${index}`]),
    [education],
  );

  // const getHealthDataWithIndex = (healthLevelInfo: any, indexs: number, isPercent: boolean = false) => {
  //   return healthLevelInfo.find((fi: any) => fi.levelNo === hearthLevelsKeys[indexs])?.[
  //     isPercent ? 'percent' : 'userCount'
  //   ];
  // };

  const getMarriageWithIndex = useCallback(
    (index: number, isPecent = false) =>
      isPecent ? marriagePercent[`marriage${index}`] : marriage[`marriage${index}`],
    [marriage],
  );

  let totalDir = measureList.map((item: any) => item.dimensions.length);
  if (totalDir.length !== 0) {
    totalDir = totalDir.reduce((b: number, a: number) => b + a);
  } else {
    totalDir = 0;
  }

  return (
    <View className={styles.container}>
      {/* 展示顶部 */}
      <View className={styles.header}>
        <Text>{teamName}</Text>
        <Text>团体心理健康评估报告</Text>
        <Text>Psychological Health Management Assessment Report</Text>
        <Text>{createdTime}</Text>
      </View>
      {/* 展示评估信息 */}
      <View className={styles.tagContent}>
        <View>
          <Text>华西心理评估中心</Text>
          <Text>Huaxi PAC</Text>
        </View>
        <View>
          <AtIcon prefixClass="icon" value="fengxian" size="16" />
        </View>
      </View>
      {/* 展示声明 */}
      <View className={styles.statement}>
        <View className={styles.beforeTitle}>
          <Text>声明</Text>
        </View>
        <View className={styles.textContent}>
          有效数据必须符合以下三个标准：在规定时间内完成测试，并提交测试结果；认真诚实作答；没有刻意掩饰自己的状态。
          所有评估结果是基于参加测试人员测评分数提示的结果，如果测评分数不能代表参加测试人员真实情况，则评估结果对参加测试人员不具有针对性。
          严格保护参加测试人员的隐私，对参加心理测评人员的个人测试结果完全保密，在进行团体分析时，不泄漏任何涉及隐私的信息。
          以下报告中的结果分析只是基于该团体的量表评估数据结果，可能会因未能收集该团体更多的信息导致报告结果与实际情况不完全相符，请根据实际情况取舍。
          本次评估结果仅作为心理健康状况筛查使用，不作为心理诊断依据
        </View>
      </View>
      {/* 展示心理体检情况 */}
      <View className={styles.mentalHealth}>
        <View className={styles.beforeTitle}>
          <Text>一、心理体检概况</Text>
        </View>
        <View className={styles.textContent}>
          本报告为{teamName}分析选用{measureList.map((item: any) => item.name).join('、')}，一共从{totalDir}
          个方面全方位的对心理健康进行筛查。根据测评结果数据，将测试者的心理健康状态划分为{riskLevels.length}个水平，即：{riskLevels.map((riskDesc: any, riskIndex: number) => {
          if (riskIndex !== 0 && riskIndex === riskLevels.length - 1) {
            return `和${riskDesc}`;
          }
          return `${riskDesc}、`;
        })}
        </View>
        <View className={styles.secondTitle}>1.1 心理体检人员基本信息</View>
        {/* 性别数据展示 */}
        <TeamTestReportItem
          thirdTitle="1.1.1 性别统计分布"
          Content={
            <View className={styles.textContent}>
              {teamName}参加此次心理体检的人员共{userCount}人，其中男性{manNum}人，女性{womanNum}人。年龄区间为{minAge}-
              {maxAge}岁，平均年龄为{avgAge}岁，标准差为{standardDeviation}。（见表1.1.1及图1.1.1）
            </View>
          }
          introTitle="表1.1.1参试人员性别统计分布表"
          chartTitle="表1.1.1参试人员性别统计分布图"
          tableHeaderList={['男', '女', '总数']}
          tableHeaderData={[
            {
              title: '人数',
              data: [manNum, womanNum, userCount],
            },
            {
              title: '百分比',
              data: [manPercent, womanPercent, '100%'],
            },
          ]}
          charDatas={[
            {
              charData: [
                {
                  item: '男',
                  count: manNum,
                },
                {
                  item: '女',
                  count: womanNum,
                },
              ],
              maxCount: userCount,
            },
          ]}
        />
        {/* 学历数据展示 */}
        <TeamTestReportItem
          thirdTitle="1.1.2 学历统计分布"
          Content={<View className={styles.textContent}>表1.1.2和图1.1.2为{teamName}参试人员学历统计分布情况</View>}
          introTitle="表1.1.2参试人员学历统计分布表"
          chartTitle="表1.1.2参试人员学历统计分布图"
          tableHeaderList={[
            '小学以下',
            '小学',
            '初中',
            '高中',
            '中专',
            '大专',
            '本科',
            '硕士',
            '博士',
            '学龄前',
            '总数',
          ]}
          tableHeaderData={[
            {
              title: '人数',
              data: [
                getEducationWithIndex(0),
                getEducationWithIndex(1),
                getEducationWithIndex(2),
                getEducationWithIndex(3),
                getEducationWithIndex(4),
                getEducationWithIndex(5),
                getEducationWithIndex(6),
                getEducationWithIndex(7),
                getEducationWithIndex(8),
                getEducationWithIndex(9),
                userCount,
              ],
            },
            {
              title: '百分比',
              data: [
                getEducationWithIndex(0, true),
                getEducationWithIndex(1, true),
                getEducationWithIndex(2, true),
                getEducationWithIndex(3, true),
                getEducationWithIndex(4, true),
                getEducationWithIndex(5, true),
                getEducationWithIndex(6, true),
                getEducationWithIndex(7, true),
                getEducationWithIndex(8, true),
                getEducationWithIndex(9, true),
                '100%',
              ],
            },
          ]}
          charDatas={[
            {
              charData: [
                {
                  item: '小学以下',
                  count: getEducationWithIndex(0),
                },
                {
                  item: '小学',
                  count: getEducationWithIndex(1),
                },
                {
                  item: '初中',
                  count: getEducationWithIndex(2),
                },
                {
                  item: '高中',
                  count: getEducationWithIndex(3),
                },
                {
                  item: '中专',
                  count: getEducationWithIndex(4),
                },
                {
                  item: '大专',
                  count: getEducationWithIndex(5),
                },
                {
                  item: '本科',
                  count: getEducationWithIndex(6),
                },
                {
                  item: '硕士',
                  count: getEducationWithIndex(7),
                },
                {
                  item: '博士',
                  count: getEducationWithIndex(8),
                },
                {
                  item: '学龄前',
                  count: getEducationWithIndex(9),
                },
              ],
              maxCount: userCount,
            },
          ]}
        />
        {/* 婚姻数据展示 */}
        <TeamTestReportItem
          thirdTitle="1.1.3 婚姻统计分布"
          Content={<View className={styles.textContent}>表1.1.3和图1.1.3为{teamName}参试人员学历婚姻分布情况</View>}
          introTitle="表1.1.3参试人员婚姻统计分布表"
          chartTitle="表1.1.3参试人员婚姻统计分布图"
          tableHeaderList={['已婚', '未婚', '离异', '丧偶', '<18岁不涉及', '其他', '总数']}
          tableHeaderData={[
            {
              title: '人数',
              data: [
                getMarriageWithIndex(0),
                getMarriageWithIndex(1),
                getMarriageWithIndex(2),
                getMarriageWithIndex(3),
                getMarriageWithIndex(4),
                getMarriageWithIndex(5),
                userCount,
              ],
            },
            {
              title: '百分比',
              data: [
                getMarriageWithIndex(0, true),
                getMarriageWithIndex(1, true),
                getMarriageWithIndex(2, true),
                getMarriageWithIndex(3, true),
                getMarriageWithIndex(4, true),
                getMarriageWithIndex(5, true),
                '100%',
              ],
            },
          ]}
          charDatas={[
            {
              charData: [
                {
                  item: '已婚',
                  count: getMarriageWithIndex(0),
                },
                {
                  item: '未婚',
                  count: getMarriageWithIndex(1),
                },
                {
                  item: '离异',
                  count: getMarriageWithIndex(2),
                },
                {
                  item: '丧偶',
                  count: getMarriageWithIndex(3),
                },
                {
                  item: '<18岁不涉及',
                  count: getMarriageWithIndex(4),
                },
                {
                  item: '其他',
                  count: getMarriageWithIndex(5),
                },
              ],
              maxCount: userCount,
            },
          ]}
        />
        <View className={styles.secondTitle}>1.2 心理健康评估量表简介</View>
        <View className={styles.textContent}>
          {measureList.map((item: any, index: number) => {
            return (
              <View key={String(index + 1)} className={styles.richTextContent}>
                {index + 1}.<View dangerouslySetInnerHTML={{ __html: item.introduce }}></View>
              </View>
            );
          })}
        </View>
      </View>
      {/* 展示心理健康评估数据分析报告 */}
      {
        riskLevels.length !== 0 && (
          <View className={styles.statement}>
            <View className={styles.beforeTitle}>
              <Text>二、心理健康评估数据分析报告</Text>
            </View>
            {measureList
              .filter((fi: any) => fi.dimensions.length !== 0)
              .map((item: any, index: number) => {
              const firstIndex = index + 2;
              const {
                name,
                userCount: testUserCount, // 当前测评的用户总数
                dimensions, // 维度数组
                comments,
                positivePercent = '0%', // 总体阳性率
              } = item;

              const getRiskDataWithIndexOne = (indexs: number, isPercent: boolean = false) =>
                comments[indexs]?.[isPercent ? 'percent' : 'userCount'];

              const riskDescStr = comments.map(
                (commentItem: any) => commentItem.riskDesc,
              );

              return (
                <View key={String(index)}>
                  <View className={styles.secondLevelTitle}>
                    {firstIndex}.1 {name}
                  </View>
                  <TeamTestReportItem
                    thirdTitle={`${firstIndex}.1.1 参试人员整体心理健康状态分布`}
                    Content={
                      <View className={styles.textContent}>
                        根据个人测评数据结果展示，目前有
                        {
                          comments.map((riskInlineItem: any) => {
                            return `${riskInlineItem.userCount}人处于${riskInlineItem.riskDesc}，`;
                          })
                        }总体阳性率为
                        {positivePercent}（见表2.1.1及图2.1.1）
                      </View>
                    }
                    introTitle={`表${firstIndex}.1.1参试人员心理健康状况分布表`}
                    chartTitle={`表${firstIndex}.1.1参试人员心理健康状况分布图`}
                    tableHeaderList={[
                      ...riskDescStr,
                      '总数',
                    ]}
                    tableHeaderData={[
                      {
                        title: '人数',
                        data: [
                          ...comments.map((info, itemIndex: number) =>
                            info.userCount,
                          ),
                          testUserCount,
                        ],
                      },
                      {
                        title: '百分比',
                        data: [
                          ...comments.map((info, itemIndex: number) =>
                            info.percent,
                          ),
                          '100%',
                        ],
                      },
                    ]}
                    charDatas={[
                      {
                        charData: riskDescStr.map(
                          (riskLevelsItem: any, riskLevelsItemIndex: number) => {
                            return {
                              item: riskLevelsItem,
                              count: getRiskDataWithIndexOne(riskLevelsItemIndex),
                            };
                          },
                        ),
                        maxCount: userCount,
                      },
                    ]}
                  />
                  {/* 参试人员心理健康因子 */}
                  {
                    dimensions.map((dimensionItem: any, dimensionItemIndex: number) => {
                      const titleIndexStr: string = `${firstIndex}.1.${index + 1}.${
                        dimensionItemIndex + 1
                      }`;
                      const { comments: inlineRisks, description, name: inlineName } = dimensionItem;
                      const riskDescStrArr: string[] = inlineRisks.map(
                        (inlineItem: any) => inlineItem.riskDesc,
                      );
                      const riskDescStrr: string = riskDescStrArr.join('、');
                      return <TeamTestReportItem
                        key={`dimensionItem${riskDescStrr}`}
                        thirdTitle={`${titleIndexStr} 参试人员各因子健康状况分布`}
                        Content={
                          <View className={styles.textContent}>
                            表{titleIndexStr}列出参试人员{name}
                            {inlineRisks.length}
                            因子{riskDescStrr}症状的人数分布与百分比。图
                            {titleIndexStr}画出
                            {inlineRisks.length}
                            因子健康状况人数分布，并较详细的描述各因子的症状表现。
                          </View>
                        }
                        introTitle={`${titleIndexStr} 参试人员心理健康状况分布表`}
                        chartTitle={`${titleIndexStr} 参试人员各因子健康状况分布图`}
                        // tableHeaderList={[riskDescStrArr]}
                        tableHeaderList={[]}
                        tableHeaderListClass={['人数', '比例']}
                        tableHeaderListClassTitle={inlineName}
                        tableHeaderData={inlineRisks.map((inlineItem: any) => {
                          return {
                            title: inlineItem.riskDesc,
                            data: [inlineItem.userCount, inlineItem.percent],
                          };
                        })}
                        charDatas={[
                          {
                            charData: inlineRisks.map((riskLevelsItem: any) => {
                              return {
                                item: riskLevelsItem.riskDesc,
                                count: riskLevelsItem.userCount,
                              };
                            }),
                            rightContent: (
                              <View className={styles.rightContent}>
                                <View>
                                  <Text>{name}</Text>
                                  {description}
                                </View>
                                <View>
                                  如左图中，测试结果显示：
                                  {inlineRisks.map((inlineRisksItem: any) => {
                                    const { userCount: inlineUserCount, riskDesc, percent } =
                                      inlineRisksItem;
                                    return `${inlineUserCount}位${riskDesc}占${percent}；`;
                                  })}{' '}
                                </View>
                              </View>
                            ),
                            maxCount: inlineRisks
                              .map((riskInfo: any) => riskInfo.userCount)
                              .reduce((b: any, a: any) => {
                                return b || 0 + a || 0;
                              }, 0),
                          }
                        ]}
                      />;
                    })
                  }
                </View>
              );
            })}
          </View>
        )
      }
      {/* 心理健康评估数据分析报告 */}
      <View className={styles.statement}>
        <View className={styles.beforeTitle}>
          <Text>三、心理健康评估数据分析报告</Text>
        </View>
        {measureList.map((item: any, index: number) => {
          const { name, comments, userCount: inlineUserCount, positivePercent } = item;
          return (
            <View key={String(index)} className={`${styles.textContent} ${styles.marginTop20}`}>
              {teamName}参加{name}心理健康评测的人员共{inlineUserCount}
              人。根据测评数据统计结果发现，
              {comments.map((riskInlineItem: any) => {
                return `${riskInlineItem.userCount}的人处于${riskInlineItem.riskDesc}，`;
              })}
              数据展示，{teamName}
              此次心理健康状况筛查的总体阳性率为{positivePercent}。
            </View>
          );
        })}
        {/* 展示对应的评阅信息 */}
        {auditComment && (
          <View
            className={`${styles.textContent} ${styles.marginTop20}`}
            dangerouslySetInnerHTML={{ __html: auditComment }}
          ></View>
        )}
      </View>
    </View>
  );
};

export default TeamTestReport;
